let db = wx.cloud.database()

//登录
export const login = (d) => {
  return new Promise((resolve, reject) => {
    db.collection('zyzl_userList').where(d).get().then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

//注册
export const register = (d) => {
  return new Promise(async (resolve, reject) => {
    const user = await db.collection('zyzl_userList').where({
      user: d.user
    }).get()
    console.log(user.data)
    if (user.data.length == 0) {
      const res = await db.collection('zyzl_userList').add({
        data: d
      })
      resolve(1)
    } else {
      resolve(0)
      wx.showToast({
        title: '账户已被注册',
        icon: 'none'
      })
    }
  })
}

//新增使用记录
export const addRecord = (d) => {
  return new Promise((resolve, reject) => {
    db.collection('recordList').add({
      data: d
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}
//编辑使用记录
export const editRecord = (d) => {
  return new Promise((resolve, reject) => {
    db.collection('recordList').doc(d._id).update({
      data: {
        evaluate: d.evaluate
      }
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

//获取记录
export const recordList = (d) => {
  return new Promise((resolve, reject) => {
    db.collection('recordList').where({
      user: d.user
    }).skip((d.num)).limit(10).get().then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

//通过id查询记录详情
export const getRecordDetail = (d) => {
  return new Promise((resolve, reject) => {
    db.collection('recordList').doc(d._id).get().then(res => {
      resolve(res.data[0])
    }).catch(err => {
      reject(err)
    })
  })
}
//地图引用
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const getStorage = (key) => {
  try {
    var v = wx.getStorageSync(key);
    return v;
  } catch (e) {
    return [];
  }
}
const setStorage = (key, cont) => {
  wx.setStorage({
    key: key,
    data: cont
  })
}
module.exports = {
  formatTime: formatTime,
  getStorage: getStorage,
  setStorage: setStorage,
  login:login,
  register:register
}
